package com.oracle.sbdb.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import com.oracle.sbdb.bo.BugInfoBo;
import com.oracle.sbdb.bo.UpdatesBo;
import com.oracle.sbdb.model.BugInfo;
import com.oracle.sbdb.servlet.model.BugUpdates;
import com.oracle.sbdb.util.JSONUtility;

/**
 * Servlet implementation class AddUpdates
 */
@WebServlet("/addUpdates")
public class AddUpdates extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public AddUpdates() {
		super();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String requestParam = request.getParameter("updates");
		String reponseContent = addUpdates(requestParam);
		PrintWriter out = response.getWriter();
		out.write(reponseContent);
		out.flush();
		out.close();
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		JSONObject requestJson = JSONUtility.getRequestString(request);
		String requestParam = requestJson.getString("updates");
		String reponseContent = addUpdates(requestParam);
		PrintWriter out = response.getWriter();
		out.write(reponseContent);
		out.flush();
		out.close();

	}

	private String addUpdates(String requestParam) {
		boolean status = false;
		try {
			if (requestParam != null) {
				BugUpdates bugUpdates = JSONUtility.json2Bean(requestParam,
						BugUpdates.class);
				if (bugUpdates != null) {
					bugUpdates.setCurrentTime();
					status = UpdatesBo.INSTANCE.insert(bugUpdates);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		JSONObject res = new JSONObject();
		res.put("Status", status ? "Success" : "Fail");
		return res.toString();
	}
}
